(function($) {
    jQuery.fn.extend({
        html5_qrcode: function(qrcodeSuccess, qrcodeError, videoError) {
            return this.each(function() {
                var currentElem = $(this);

                var height = currentElem.height();
                var width = currentElem.width();

                if (height == null) {
                    height = 250;
                }

                if (width == null) {
                    width = 300;
                }

                var vidElem = $('<video width="' + width + 'px" height="' + height + 'px"></video>').appendTo(currentElem);
                var canvasElem = $('<canvas id="qr-canvas" width="' + (width - 2) + 'px" height="' + (height - 2) + 'px" ></canvas>').appendTo(currentElem);

                var video = vidElem[0];
                var canvas = canvasElem[0];
                var context = canvas.getContext('2d');
                var localMediaStream;

                var scan = function() {
                    if (localMediaStream) {
                        
                        context.drawImage(video, 0, 0, 307, 250);

                        try {
                            alert("qrcode")
                            qrcode.decode();
                        } catch (e) {
                            qrcodeError(e, localMediaStream);
                        }

                        $.data(currentElem[0], "timeout", setTimeout(scan, 500));

                    } else {
                        $.data(currentElem[0], "timeout", setTimeout(scan, 500));
                    }
                };//end snapshot function

                window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
                navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;

                var successCallback = function(stream) {
                    video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
                    localMediaStream = stream;
                    $.data(currentElem[0], "stream", stream);

                    video.play();
                    $.data(currentElem[0], "timeout", setTimeout(scan, 1000));
                };

                var exArray = []; //存储设备源ID  
                MediaStreamTrack.getSources(function(sourceInfos) {
                    for (var i = 0; i != sourceInfos.length; ++i) {
                        var sourceInfo = sourceInfos[i]; //这里会遍历audio,video，所以要加以区分
                        if (sourceInfo.kind === 'video') { exArray.push(sourceInfo.id); }
                    }
                    alert(1)
                     alert(exArray)
                     alert(exArray[0] );
                     if(navigator.getUserMedia) { // Standard
                         navigator.getUserMedia({'video': {  
                             'optional': [{  
                                 'sourceId': exArray[1] //0为前置摄像头，1为后置  
                             }]  
                         },  
                         'audio':true }, successCallback, function(error) {
                             videoError(error, localMediaStream);
                         });
                     } 
                     // else if(navigator.webkitGetUserMedia) { // WebKit-prefixed
     
                     //     navigator.webkitGetUserMedia({video: true}, successCallback, function(error) {
                     //         videoError(error, localMediaStream);
                     //     });
                     // } else if(navigator.mozGetUserMedia) { // WebKit-prefixed
                     //     navigator.mozGetUserMedia({video: true}, successCallback, function(error) {
                     //         videoError(error, localMediaStream);
                     //     });
                     // }
                      else {
                         alert(1);
                         console.log('Native web camera streaming (getUserMedia) not supported in this browser.');
                     }
                });
                // Put video listeners into place
                

                // Call the getUserMedia method with our callback functions
                // if (navigator.getUserMedia) {
                //     console.log(111)
                //     navigator.getUserMedia({video: true}, successCallback, function(error) {
                //         videoError(error, localMediaStream);
                //     });
                // } else {
                //     console.log('Native web camera streaming (getUserMedia) not supported in this browser.');
                //     // Display a friendly "sorry" message to the user
                // }

                qrcode.callback = function (result) {
                    console.log(result)
                    qrcodeSuccess(result, localMediaStream);
                };
            }); // end of html5_qrcode
        },
        html5_qrcode_stop: function() {
            return this.each(function() {
                //stop the stream and cancel timeouts
                $(this).data('stream').stop();
                clearTimeout($(this).data('timeout'));
            });
        }
    });
})(jQuery);
